from selenium.webdriver.common.by import By

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait


class Base:
    def __init__(self, driver):
        self.driver = driver

        self.loctors_method = {"id":By.ID,"name":By.NAME,"xpath":By.XPATH,"class name":By.CLASS_NAME,"link text":By.LINK_TEXT,"css":By.CSS_SELECTOR,"tag name":By.TAG_NAME,"partial link text":By.PARTIAL_LINK_TEXT}

    def find_element(self,loc_method,loc):   #定位方式、元素值
        try:
            element = WebDriverWait(self.driver,10,0.5).until(EC.presence_of_element_located((self.loctors_method[loc_method],loc)))
            return element
        except Exception as e:
            return "元素超时，没有找到：%s" % e

    def find_elements(self,loc_method,loc,num):
        try:
            ele = WebDriverWait(self.driver,10,0.5).until(EC.presence_of_all_elements_located((self.loctors_method[loc_method],loc)))[num]
            return ele
        except Exception as e:
            return "元素超时，没有找到：%s"%e


    def click_element(self,loc_method,loc):
        self.find_element(loc_method,loc).click()

    def click_elements(self,loc_method,loc,num):
        self.find_elements(loc_method,loc,num).click()


        #断言
    def get_text(self,loc_method,loc):
        ele = self.find_element(loc_method,loc)
        text = ele.text
        return text
    def get_texts(self,loc_method,loc,num):
        ele = self.find_elements(loc_method,loc,num)
        text = ele.text
        return text


#句柄切换
    def win_switch(self, num):
        win = self.driver.window_handles
        self.driver.switch_to.window(win[num])


# alert网页的弹窗处理
    def alert_switch(self,type:int):
        alert = self.driver.switch_to.alert
        if type == 1:
            alert.accept()
        elif type == 2:
            alert.dismiss()


# iframe内联框架处理
    def iframe_switch(self,loc_method,loc,num):
        iframe = self.find_elements(loc_method,loc,num)
        self.driver.switch_to.frame(iframe)


# 输入文本内容
    def input_text(self,loc_method,loc,content):
        text = self.find_element(loc_method,loc)
        text.clear()
        text.send_keys(content)

    # 输入文本内容
    def input_texts(self,loc_method,loc,num,content):
        text = self.find_elements(loc_method,loc,num)
        text.clear()
        text.send_keys(content)

    def refresh(self):
        self.driver.refresh()

























